package com.auto.learning.fragment;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.activity.PlayActivity;
import com.auto.learning.activity.ReadBookActivity;
import com.auto.learning.adapter.ReadFragmentChapterAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ReadModeBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.bean.ShareBean;
import com.auto.learning.bean.UserVipInfo;
import com.auto.learning.event.BuySuccessEvent;
import com.auto.learning.event.CollectEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.ProgressEvent;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.pay.UserBuyUtils;
import com.auto.learning.service.DownLoadManager;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.tools.Utils;
import com.auto.learning.view.MyListView;
import com.auto.learning.view.RoundImageView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

/**
 * 第一版本ReadFragment
 * @author wangjianjun
 */
public class ReadFragment extends Fragment {
	
	private final static int GETCACHEDATA_SUCCESS = 2;
	private final static int DOWNLOAD_PROGRESS = 3;
	public final static int BUY_SUCCESS = 4;
	private LinearLayout rel_bottom;
	private LinearLayout linear_download;
	private RelativeLayout linear_read_main;
	private ArrayList<SelectionVo> chapterList = new  ArrayList<SelectionVo>();
	private ArrayList<SelectionVo> chapterListEn = new  ArrayList<SelectionVo>();
	private MyListView listview_chapters_china,listview_chapters_en;
	private ReadFragmentChapterAdapter chinaAdapter,enAdapter;
	private int bookId;
	private ReadModeBean readModeBean = new ReadModeBean();
	private PullToRefreshScrollView main_scroll;
	private ImageView image_collect,f_image_play,f_image_guoqi,image_download,image_price;
	private RoundImageView f_image_face;
	private TextView tv_xcy,tv_collect,tv_download,tv_bookname,tv_slogan,tv_listen_number,tv_shoucang_number,tv_pinglun_number,about,tv_goldword,tv_chapter,tv_chapter_en,tv_need_price;
	DisplayImageOptions options;
	
	private TextView tv_comment_list,tv_read_all;
	private View tv_comment_line,tv_read_all_line, tv_anchor_all_line;
	private RelativeLayout rel_right,rel_mid;
	
	private Handle handle = new Handle(getActivity()){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result = (ResponeResult)msg.obj;
				readModeBean = new Gson().fromJson(result.getData(), new TypeToken<ReadModeBean>(){}.getType());
				showView();
				Cache.cacheReadMode2Local(readModeBean);
				if (main_scroll != null) {
					main_scroll.onRefreshComplete();
				}
				break;
			case GETCACHEDATA_SUCCESS:
				if (readModeBean.getBookId() != 0) {
					showView();
					if (TemporaryVariable.downLoadedList.contains(bookId)) {
						image_download.setBackgroundResource(R.drawable.xiazaiok);
						tv_download.setText("已下载");
					}else {
						image_download.setBackgroundResource(R.drawable.xiazai2);
						tv_download.setText("下载");
					}
				}
				getData();
				break;
			case DOWNLOAD_PROGRESS:
				ProgressEvent event = (ProgressEvent)msg.obj;
				if (event.getBookId() == bookId) {
					/*if (event.getCurrentRatio() == 100) {
						image_download.setBackgroundResource(R.drawable.xiazaiok);
						tv_download.setText("已下载");
					}else {
						linear_download.setEnabled(false);
						tv_download.setText(event.getCurrentRatio()+"%");
						image_download.setBackgroundResource(R.anim.download_stute);
						AnimationDrawable _animaition = (AnimationDrawable)image_download.getBackground();
						_animaition.setOneShot(false);   
						_animaition.start();
					}*/
					
					if (buttonList != null && buttonList.size() == 1) {
						if (event.getCurrentRatio() == 100) {
							handle.postDelayed(new Runnable() {
								@Override
								public void run() {
									dealBottom();
								}
							}, 500);
						}else {
							buttonList.get(0).setText(event.getCurrentRatio()+"%");
						}
					}
				}
				break;
			case HttpRequestHelper.COLLECT_SUCCESS:
				tv_collect.setText("已收藏");
				image_collect.setImageResource(R.drawable.shoucang_ok);
				readModeBean.setIsFavor(2);
				ResponeResult collect_result = (ResponeResult)msg.obj;
				CollectEvent collect_event = new CollectEvent();
				collect_event.setBookId(Integer.parseInt(collect_result.getData()));
				collect_event.setCollect(true);
				EventBus.getEventBus(HttpRequestHelper.COLLECT_EVENT).post(collect_event);
				break;
			case HttpRequestHelper.GETDATA_FAIL:
			case HttpRequestHelper.COLLECT_FAIL:
				try {
					if (main_scroll != null) {
						main_scroll.onRefreshComplete();
					}
					if (msg.obj != null) {
						CommonMethod.makeNotice(getActivity(), msg.obj+"");
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case BUY_SUCCESS:
				if (readModeBean != null) {
					if (msg.arg1 == 0 || readModeBean.getBookId() == msg.arg1) {
						readModeBean.setNeedBuy(1);
						((PlayActivity)getActivity()).setNeedBuy(1);
						dealBottom();
					}
				}
				break;
			}
		};
	};
	
	
	private void showView(){
		if (readModeBean == null) {
			return;
		}
		try {
			ImageLoader.getInstance().displayImage(readModeBean.getFaceImgPlay(), f_image_face,options);
			ImageLoader.getInstance().displayImage(readModeBean.getNationImg(), f_image_guoqi);
			tv_xcy.setText(readModeBean.getSlogan()+"");
			tv_bookname.setText(readModeBean.getBookName()+"");
			tv_slogan.setText(readModeBean.getAuthor()+"");
			tv_listen_number.setText(readModeBean.getListenNum()+"");
			tv_shoucang_number.setText(readModeBean.getFavorNum()+"");
			tv_pinglun_number.setText(readModeBean.getCommentNum()+"");
			if (!TextUtils.isEmpty(readModeBean.getAbout())) {
				about.setText(Html.fromHtml(readModeBean.getAbout()+""));
			}
			if (!TextUtils.isEmpty(readModeBean.getGoldWord())) {
				tv_goldword.setText(Html.fromHtml(readModeBean.getGoldWord()+""));
			}
			tv_need_price.setText(readModeBean.getPriceTag()+"");
			if (readModeBean.getFree() == 1) {
				image_price.setVisibility(View.VISIBLE);
				tv_need_price.setVisibility(View.VISIBLE);
			} else {
				image_price.setVisibility(View.GONE);
				tv_need_price.setVisibility(View.GONE);
			}
			((PlayActivity)getActivity()).setNeedBuy(readModeBean.getNeedBuy());
			((PlayActivity)getActivity()).setCanRead(readModeBean.getCanRead());
			dealBottom();
			updateUi();
			initBottomList(readModeBean.getSectionList());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	List<Button> buttonList;
	
	private void dealBottom(){
		if (TemporaryVariable.downLoadedList.contains(readModeBean.getBookId())) {
			rel_bottom.setVisibility(View.GONE);
			buttonList = Utils.setBookType(rel_bottom, ((PlayActivity)getActivity()).getTypeList(1), getActivity());
		}else {
			if (readModeBean.getNeedBuy() == 1) {
				buttonList = Utils.setBookType(rel_bottom, ((PlayActivity)getActivity()).getTypeList(3), getActivity());
			}else {
				UserVipInfo vipInfo = MyUserInfo.getInstance().getUserInfoBean().getVipInfo();
				if (vipInfo != null) {
					switch (vipInfo.getVipType()) {
					case 1:
						buttonList = Utils.setBookType(rel_bottom, ((PlayActivity)getActivity()).getTypeList(4), getActivity());
						break;
					case 2:
					case 3:
						buttonList = Utils.setBookType(rel_bottom, ((PlayActivity)getActivity()).getTypeList(2), getActivity());
						break;
					}
				}else {
					buttonList = Utils.setBookType(rel_bottom, ((PlayActivity)getActivity()).getTypeList(2), getActivity());
				}
			}
		}
	}
	
	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.read_fragment, null);
		initImageLoader();
		initView(view);
		registerEvent();
		setUserVisibleHint(true);
		return view;
	}
	
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			readModeBean = ((PlayActivity)getActivity()).getReadModeFromCommentFragment();
			if (readModeBean != null && readModeBean.getBookId() > 0 && !TextUtils.isEmpty(readModeBean.getAbout())) {
				showView();
			}else {
				getPageCache();
			}
		}
	}
	
	private void getData(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(bookId)));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.READ_MODE, params, handle, HttpRequestHelper.GETDATA_SUCCESS, HttpRequestHelper.GETDATA_FAIL);
	}
	private void initView(View view){
		image_price = (ImageView) view.findViewById(R.id.image_price);
		tv_need_price = (TextView) view.findViewById(R.id.tv_need_price);
		image_price.setVisibility(View.GONE);
		tv_need_price.setVisibility(View.GONE);
		rel_bottom=(LinearLayout) view.findViewById(R.id.rel_bottom);
		rel_right = (RelativeLayout) view.findViewById(R.id.rel_right);
		rel_mid = (RelativeLayout) view.findViewById(R.id.rel_mid);
		tv_comment_list = (TextView) view.findViewById(R.id.tv_comment_list);
		tv_comment_line =  view.findViewById(R.id.tv_comment_line);
		tv_read_all_line =  view.findViewById(R.id.tv_read_all_line);
		tv_anchor_all_line =  view.findViewById(R.id.tv_anchor_all_line);
		tv_read_all = (TextView) view.findViewById(R.id.tv_read_all);
		tv_comment_list.setTextColor(getResources().getColor(R.color.white));
		tv_read_all_line.setVisibility(View.VISIBLE);
		tv_read_all.setTextColor(getResources().getColor(R.color.main_green_color));
		tv_comment_line.setVisibility(View.INVISIBLE);
		tv_anchor_all_line.setVisibility(View.INVISIBLE);
		rel_right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				((PlayActivity)getActivity()).checkToComment();
			}
		});
		rel_mid.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				((PlayActivity)getActivity()).checkToAnchor();
			}
		});
		
		tv_xcy = (TextView) view.findViewById(R.id.tv_xcy);
		main_scroll = (PullToRefreshScrollView) view.findViewById(R.id.main_scroll);
		main_scroll.setMode(Mode.PULL_FROM_START);
		main_scroll.setScrollingWhileRefreshingEnabled(true);
		main_scroll.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
				getPageCache();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
				
			}
		});
	
		
		linear_read_main = (RelativeLayout) view.findViewById(R.id.linear_read_main);
		linear_read_main.getBackground().setAlpha(200);
		listview_chapters_china = (MyListView) view.findViewById(R.id.listview_chapters_china);
		listview_chapters_en = (MyListView) view.findViewById(R.id.listview_chapters_en);
		chinaAdapter = new ReadFragmentChapterAdapter(getActivity(), chapterList, 1);
		enAdapter = new ReadFragmentChapterAdapter(getActivity(), chapterListEn, 2);
		listview_chapters_china.setAdapter(chinaAdapter);
		listview_chapters_en.setAdapter(enAdapter);
		listview_chapters_china.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				MusicPlayManager manager = MusicPlayManager.getInstance(getActivity());
				if(((PlayActivity)getActivity()).getNeedBuy() == 2 && !TemporaryVariable.downLoadedList.contains(bookId)){
					if(manager.getPlayList() != null && manager.getPlayList().size() > 0){
						int ids[] = manager.isPlayingBookId();
						if (ids[0] != bookId) {
							new UserBuyUtils(((Activity)getActivity()),bookId, readModeBean.getPriceTag(),UserBuyUtils.OPERATOR_READ,readModeBean.getBookName()).buy();
							return;
						}
					}else{
						new UserBuyUtils(((Activity)getActivity()), bookId, readModeBean.getPriceTag(),UserBuyUtils.OPERATOR_READ,readModeBean.getBookName()).buy();
						return;
					}
				}
				StatService.onEvent(getActivity(), "LogEventDetailChapterBtnClick", "详情页的章节点击");
				Intent intent = new Intent(getActivity(), ReadBookActivity.class);
				intent.putExtra("descList", (Serializable)chapterList);
				intent.putExtra("position", position);
				intent.putExtra("type", "c");
				intent.putExtra("bookId", bookId);
				intent.putExtra("bookName", readModeBean.getBookName());
				intent.putExtra("slogan", readModeBean.getSlogan());
				intent.putExtra("faceImg", readModeBean.getFaceImg());
				intent.putExtra("faceImgPlay", readModeBean.getFaceImgPlay());
				startActivity(intent);
				
			}
		});
		listview_chapters_en.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				MusicPlayManager manager = MusicPlayManager.getInstance(getActivity());
				if(((PlayActivity)getActivity()).getNeedBuy() == 2 && !TemporaryVariable.downLoadedList.contains(bookId)){
					if(manager.getPlayList() != null && manager.getPlayList().size() > 0){
						int ids[] = manager.isPlayingBookId();
						if (ids[0] != bookId) {
							new UserBuyUtils(((Activity)getActivity()),bookId, readModeBean.getPriceTag(),UserBuyUtils.OPERATOR_READ,readModeBean.getBookName()).buy();
							return;
						}
					}else{
						new UserBuyUtils(((Activity)getActivity()), bookId, readModeBean.getPriceTag(),UserBuyUtils.OPERATOR_READ,readModeBean.getBookName()).buy();
						return;
					}
				}
				StatService.onEvent(getActivity(), "LogEventDetailChapterBtnClick", "详情页的章节点击");
				Intent intent = new Intent(getActivity(),ReadBookActivity.class);
				intent.putExtra("descList", (Serializable)chapterListEn);
				intent.putExtra("position", position);
				intent.putExtra("type", "e");
				intent.putExtra("bookId", bookId);
				intent.putExtra("bookName", readModeBean.getBookName());
				intent.putExtra("slogan", readModeBean.getSlogan());
				intent.putExtra("faceImg", readModeBean.getFaceImg());
				intent.putExtra("faceImgPlay", readModeBean.getFaceImgPlay());
				startActivity(intent);
			}
		});
		tv_chapter = (TextView) view.findViewById(R.id.tv_chapter);
		tv_chapter_en = (TextView) view.findViewById(R.id.tv_chapter_en);
		linear_download = (LinearLayout) view.findViewById(R.id.linear_download);
		image_download = (ImageView) view.findViewById(R.id.image_download);
		tv_download = (TextView) view.findViewById(R.id.tv_download);
		tv_collect = (TextView) view.findViewById(R.id.tv_collect);
		image_collect = (ImageView) view.findViewById(R.id.image_collect);
		if (TemporaryVariable.downLoadedList.contains(bookId)) {
			image_download.setBackgroundResource(R.drawable.xiazaiok);
			tv_download.setText("已下载");
		}else {
			image_download.setBackgroundResource(R.drawable.xiazai2);
			tv_download.setText("下载");
		}
		f_image_face = (RoundImageView) view.findViewById(R.id.f_image_face);
		f_image_play = (ImageView) view.findViewById(R.id.f_image_play);
		f_image_guoqi = (ImageView) view.findViewById(R.id.f_image_guoqi);
		tv_bookname = (TextView) view.findViewById(R.id.tv_bookname);
		tv_slogan = (TextView) view.findViewById(R.id.tv_slogan);
		tv_listen_number = (TextView) view.findViewById(R.id.tv_listen_number);
		tv_shoucang_number = (TextView) view.findViewById(R.id.tv_shoucang_number);
		tv_pinglun_number = (TextView) view.findViewById(R.id.tv_pinglun_number);
		about = (TextView) view.findViewById(R.id.about);
		tv_goldword = (TextView) view.findViewById(R.id.tv_goldword);
		
		try {
			ImageLoader.getInstance().displayImage(readModeBean.getFaceImgPlay(), f_image_face);
			ImageLoader.getInstance().displayImage(readModeBean.getNationImg(), f_image_guoqi);
		} catch (Exception e) {
			e.printStackTrace();
		}
		tv_bookname.setText(readModeBean.getBookName()+"");
		tv_slogan.setText(readModeBean.getAuthor()+"");
		tv_listen_number.setText(readModeBean.getListenNum()+"");
		tv_shoucang_number.setText(readModeBean.getFavorNum()+"");
		tv_pinglun_number.setText(readModeBean.getCommentNum()+"");
		if (!TextUtils.isEmpty(readModeBean.getAbout())) {
			about.setText(Html.fromHtml(readModeBean.getAbout()));
		}
		if (!TextUtils.isEmpty(readModeBean.getGoldWord())) {
			tv_goldword.setText(Html.fromHtml(readModeBean.getGoldWord()));
		}
		tv_goldword.setTextIsSelectable(true);
		about.setTextIsSelectable(true);
		updateUi();
		f_image_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				StatService.onEvent(getActivity(), "LogEventDetailPlayBtnClick", "详情页的题图播放");
				MusicPlayManager manager = MusicPlayManager.getInstance(getActivity());
				if (manager.getPlayList() != null && manager.getPlayList().size() > 0) {
					int ids[] = manager.isPlayingBookId();
					if (ids[0] == bookId) {
						MusicPlayManager.getInstance(getActivity()).pause();
					} else {
						if(((PlayActivity)getActivity()).getNeedBuy() == 2&&!TemporaryVariable.downLoadedList.contains(bookId)){
							new UserBuyUtils(((Activity)getActivity()), bookId, readModeBean.getPriceTag(),readModeBean.getBookName()).buy();
							return;
						}
						BookBean bookBean = new BookBean();
						bookBean.setBookId(bookId);
						bookBean.setSectionList(readModeBean != null ? readModeBean.getSectionList() : null);
						bookBean.setBookName(readModeBean.getBookName());
						bookBean.setSlogan(readModeBean.getSlogan());
						bookBean.setFaceImg(readModeBean.getFaceImg());
						bookBean.setFaceImgPlay(readModeBean.getFaceImgPlay());
						((PlayActivity) getActivity()).getLocalBook(bookBean);
					}
				} else {
					if(((PlayActivity)getActivity()).getNeedBuy() == 2&&!TemporaryVariable.downLoadedList.contains(bookId)){
						new UserBuyUtils(((Activity)getActivity()), bookId, readModeBean.getPriceTag(),readModeBean.getBookName()).buy();
						return;
					}
					BookBean bookBean = new BookBean();
					bookBean.setBookId(bookId);
					bookBean.setSectionList(readModeBean != null ? readModeBean.getSectionList() : null);
					bookBean.setBookName(readModeBean.getBookName());
					bookBean.setSlogan(readModeBean.getSlogan());
					bookBean.setFaceImg(readModeBean.getFaceImg());
					bookBean.setFaceImgPlay(readModeBean.getFaceImgPlay());
					((PlayActivity) getActivity()).getLocalBook(bookBean);
				}
			}
		});
		linear_download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addDownload();
			}
		});
		/*linear_collect = (LinearLayout) view.findViewById(R.id.linear_collect);
		linear_collect.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (readModeBean != null && readModeBean.getIsFavor() == 1) {
					HttpRequestHelper.AddCollect(getActivity(), handle, getBookId(),HttpRequestHelper.COLLECT_FAIL);
				}
			}
		});*/
		initBottomList(readModeBean.getSectionList());
		scrollView2Top();
	}
	
	public void addDownload(){
		if (readModeBean != null && !TemporaryVariable.downLoadedList.contains(readModeBean.getBookId()) && CommonMethod.checkUserLogin(getActivity())) {
			int downLoadSize = readModeBean.getDoubiSize() + readModeBean.getProSize() +readModeBean.getEnSize();
			if (downLoadSize > 0) {
				if (!TemporaryVariable.downLoadedList.contains(readModeBean.getBookId())) {
//					DownLoadManager.getInstance(getActivity()).setNeedDownLoadBookId(bookId).prepareBefore(downLoadSize);
					StatService.onEvent(getActivity(), "LogEventTypeDownloadButtonClic", "下载按钮");
					DownLoadManager.getInstance(getActivity()).setContext(getActivity()).prepareBefore(bookId,downLoadSize);
				}
			}
		}
	}
	
	/***
	 * 获取被评论书的信息
	 */
	public Map<String, Object> getCommentBookInfo(){
		Map<String, Object> map = new HashMap<String, Object>();
		if (readModeBean != null && readModeBean.getBookId() > 0) {
			map.put("bookId", readModeBean.getBookId());
			map.put("bookName", readModeBean.getBookName());
			map.put("imgFace", readModeBean.getFaceImg());
			map.put("imgFacePlay", readModeBean.getFaceImgPlay());
		}
		return map;
	}
	
	private void initBottomList(List<SelectionVo> list){
		if (list == null) {
			return;
		}
		if (chapterList != null && list.size() > 0) {
			if (TextUtils.isEmpty(list.get(0).getTitle())) {
				listview_chapters_china.setVisibility(View.GONE);
				tv_chapter.setVisibility(View.GONE);
			}else {
				listview_chapters_china.setVisibility(View.VISIBLE);
				tv_chapter.setVisibility(View.VISIBLE);
			}
			if (TextUtils.isEmpty(list.get(0).getTitleEn())) {
				listview_chapters_en.setVisibility(View.GONE);
				tv_chapter_en.setVisibility(View.GONE);
			}else {
				listview_chapters_en.setVisibility(View.VISIBLE);
				tv_chapter_en.setVisibility(View.VISIBLE);
			}
			chapterListEn.clear();
			chapterList.clear();
			chapterList.addAll(list);
			chapterListEn.addAll(list);
			for (int i = 0; i < chapterList.size(); i++) {
				if (TextUtils.isEmpty(chapterList.get(i).getTitle())) {
					chapterList.remove(i);
					i--;
				}
			}
			for (int i = 0; i < chapterListEn.size(); i++) {
				if (TextUtils.isEmpty(chapterListEn.get(i).getTitleEn())) {
					chapterListEn.remove(i);
					i--;
				}
			}
			if (chinaAdapter != null) {
				chinaAdapter.notifyDataSetChanged();
			}
			if (enAdapter != null) {
				enAdapter.notifyDataSetChanged();
			}
//			CommonMethod.setListViewUnSameHeight(listview_chapters_en);
//			CommonMethod.setListViewUnSameHeight(listview_chapters_china);
//			main_scroll.smoothScrollTo(0, 0);
			main_scroll.smoothScrollTo(0, 0);
		}
	}
	
	public void scrollView2Top(){
		handle.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				if (main_scroll != null) {
					main_scroll.smoothScrollTo(0, 0);
				}				
			}
		}, 100);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unRegisterEvent();
	}
	
	public void updateUi(){
		int playingBookId[] = MusicPlayManager.getInstance(getActivity()).isPlayingBookId();
		if (playingBookId[0] != 0 && playingBookId[0] == bookId) {
			if (playingBookId[2] == 0) 
				f_image_play.setImageResource(R.drawable.playing);
			else 
				f_image_play.setImageResource(R.drawable.play);
		} else {
			f_image_play.setImageResource(R.drawable.play);
		}
	}
	
	boolean isPlaying = false;
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		if (MusicPlayManager.getInstance(getActivity()).getPlayList() != null) {
			int ids[] = MusicPlayManager.getInstance(getActivity()).isPlayingBookId();
			if (ids[0] == bookId) {
				this.isPlaying = isPlaying;
				MusicPlayManager.getInstance(getActivity()).setPlaying(isPlaying);
				if (ids[0] != 0) {
					setBookId(ids[0]);
				}
				updateUi();
			}
		}
	}
	
	@Subscribe
	public void onEventProgress(ProgressEvent event){
		handle.obtainMessage(DOWNLOAD_PROGRESS, event).sendToTarget();
	}
	
	@Subscribe
	public void onEventBuySuccess(BuySuccessEvent buySuccessEvent){
		handle.obtainMessage(BUY_SUCCESS, buySuccessEvent.getBookId(), 0).sendToTarget();
	}
	
	public void registerEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("downloadProgress",ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_buy_success",ThreadEnforcer.MAIN).register(this);
	}
	
	public void unRegisterEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("downloadProgress",ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_buy_success",ThreadEnforcer.MAIN).unregister(this);
	}
	
	private void getPageCache(){
		
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					BookBean bean = StaticReference.mutilDBSupport.getDao(BookBean.class).queryForId(bookId);
					if (bean != null) {
						readModeBean.setBookId(bookId);
						readModeBean.setBookName(bean.getBookName());
						readModeBean.setFaceImg(bean.getFaceImg());
						readModeBean.setFaceImgPlay(bean.getFaceImgPlay());
						readModeBean.setNationImg(bean.getNationImg());
						readModeBean.setAbout(bean.getAbout());
						readModeBean.setGoldWord(bean.getGoldWord());
						readModeBean.setAuthor(bean.getAuthor());
						readModeBean.setCommentNum(bean.getCommentNum());
						readModeBean.setFavorNum(bean.getFavorNum());
						readModeBean.setListenNum(bean.getListenNum());
						readModeBean.setProSize(bean.getProSize());
						readModeBean.setEnSize(bean.getEnSize());
						readModeBean.setDoubiSize(bean.getDoubiSize());
						readModeBean.setIsFavor(bean.getIsFavor());
						readModeBean.setSlogan(bean.getSlogan());
						readModeBean.setIsNew(bean.getIsNew());
						readModeBean.setCanRead(bean.getCanRead());
						readModeBean.setFree(bean.getFree());
						readModeBean.setPriceTag(bean.getPriceTag());
						readModeBean.setNeedBuy(bean.getNeedBuy());
						List<SelectionVo> list_vo =	StaticReference.mutilDBSupport.getDao(SelectionVo.class).queryBuilder().where().eq("bookId", bookId).query();
						if (list_vo != null) {
							readModeBean.setSectionList(list_vo);
						}
					}
					handle.sendEmptyMessage(GETCACHEDATA_SUCCESS);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
	
	public ShareBean getShareValue(){
		if (TextUtils.isEmpty(readModeBean.getBookName()) || TextUtils.isEmpty(readModeBean.getSlogan())) {
			return null;
		}
		ShareBean m_share = new ShareBean();
		m_share.setBookId(bookId);
		m_share.setUrl(HttpCommonInfo.MURL + "authorware-detail?id=" + bookId);
		m_share.setTitle(readModeBean.getBookName());
		m_share.setContent(readModeBean.getSlogan());
		m_share.setImageUrl(readModeBean.getFaceImgPlay());
		return m_share;
	}
	
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.default_512)
		.showImageForEmptyUri(R.drawable.default_512)
		.showImageOnFail(R.drawable.default_512).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}
	
	public void refreData(){
		getPageCache();
	}
	
	public ReadModeBean getReadModeBean() {
		return readModeBean;
	}

	public void setReadModeBean(ReadModeBean readModeBean) {
		this.readModeBean = readModeBean;
	}
}
